package apollo.generator.common.base;

import apollo.generator.common.exception.CustomException;
import apollo.generator.common.utils.ValidateUtils;
import apollo.generator.modules.controller.AbstractController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.Validator;

/**
 * <Description>
 * 基础的处理器
 * @author Jun Lee
 * @version 1.0
 * @createDate 2020-03-27 18:15:36
 */
@Slf4j
public abstract class BaseController extends AbstractController {
    @Autowired
    private Validator validator;

    /**
     * 校验参数并抛出自定义异常
     * @param object
     * @throws CustomException
     */
    public void validator2CustomException(Object object) throws CustomException {
        ValidateUtils.castCustomException(object, validator);
    }

    /**
     * 校验参数并抛出自定义异常并且指定异常信息
     * @param object
     * @param message
     * @throws CustomException
     */
    public void validator2CustomException4ThrowCustomMessage(Object object,String message) throws CustomException {
        try {
            ValidateUtils.castCustomException(object, validator);
        } catch (CustomException e) {
            log.error(e.getMessage());
            throw new CustomException(message);
        }
    }

    /**
     * 分组校验参数并抛出自定义异常
     * @param object
     * @param groups
     * @throws CustomException
     */
    public void validatorGroups2CustomException(Object object,Class<?>... groups) throws CustomException {
        ValidateUtils.castCustomException(object, validator,groups);
    }

    /**
     * 校验参数抛出普通异常
     * @param object
     * @throws Exception
     */
    public void validator2Exception(Object object) throws Exception {
        ValidateUtils.castException(object, validator);
    }

    /**
     * 分组校验参数抛出普通异常
     * @param object
     * @param groups
     * @throws Exception
     */
    public void validator2Exception(Object object,Class<?>... groups) throws Exception {
        ValidateUtils.castException(object, validator,groups);
    }
}
